package cz.anime.ppro.beans;

import java.util.Calendar;

import javax.faces.bean.ManagedBean;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;

import cz.anime.ppro.logic.MessageComponent;
import cz.anime.ppro.logic.UserComponent;
import cz.anime.ppro.model.Message;
import cz.anime.ppro.model.Webuser;

@Component
@ManagedBean
@Scope(WebApplicationContext.SCOPE_REQUEST)
public class NewMessageBean {

	@Autowired
	private MessageComponent messageComponent;
	
	@Autowired
	private UserComponent userComponent;
	
	private String title;
	private String text;
	private String toUser;
	
	private String errorMessage;
	private boolean errorMessageExists = false;
	
	public String sendMessage(){
		Webuser webuser2 = userComponent.getUserByNick(toUser);
		if(webuser2 == null){
			errorMessage = "Uživatel neexistuje.";
			errorMessageExists = true;
			return "messagenew";
		}
		
		Webuser webuser1 = userComponent.getUserByNick(userComponent.getCurrentUsernameFromSession());
		
		Message newMesage = new Message();
		
		newMesage.setDate(Calendar.getInstance().getTime());
		newMesage.setText(getText());
		newMesage.setTitle(getTitle());
		newMesage.setWebuser1(webuser1);
		newMesage.setWebuser2(webuser2);
		
		
		
		messageComponent.saveMessage(newMesage);
		return "messageout?faces-redirect=true";
	}
	
	public String getTitle() {
		return title;
	}
	
	public void setTitle(String title) {
		this.title = title;
	}
	
	public String getText() {
		return text;
	}
	
	public void setText(String text) {
		this.text = text;
	}
	
	public String getToUser() {
		return toUser;
	}
	
	public void setToUser(String toUser) {
		this.toUser = toUser;
	}

	public String getErrorMessage() {
		return errorMessage;
	}

	public void setErrorMessage(String errorMessage) {
		this.errorMessage = errorMessage;
	}

	public boolean isErrorMessageExists() {
		return errorMessageExists;
	}

	public void setErrorMessageExists(boolean errorMessageExists) {
		this.errorMessageExists = errorMessageExists;
	}

}
